// 初始设置
let sourceDomain = 'github.com';
let targetDomain = 'bgithub.xyz';

// 从存储加载设置
chrome.storage.local.get(['sourceDomain', 'targetDomain'], function(result) {
    if (result.sourceDomain) sourceDomain = result.sourceDomain;
    if (result.targetDomain) targetDomain = result.targetDomain;
    
    // 初始化后立即设置规则
    updateRedirectRules();
    console.log(`域名跳转插件初始化: ${sourceDomain} -> ${targetDomain}`);
});

// 监听设置更新消息
chrome.runtime.onMessage.addListener(function(message) {
    if (message.action === 'settingsUpdated') {
        chrome.storage.local.get(['sourceDomain', 'targetDomain'], function(result) {
            if (result.sourceDomain) sourceDomain = result.sourceDomain;
            if (result.targetDomain) targetDomain = result.targetDomain;
            
            // 更新重定向规则
            updateRedirectRules();
            console.log(`域名跳转设置已更新: ${sourceDomain} -> ${targetDomain}`);
        });
    }
});

// 更新重定向规则
function updateRedirectRules() {
    // 移除所有现有规则
    chrome.declarativeNetRequest.getDynamicRules().then((rules) => {
        const ruleIds = rules.map(rule => rule.id);
        if (ruleIds.length > 0) {
            chrome.declarativeNetRequest.updateDynamicRules({
                removeRuleIds: ruleIds
            });
        }
    });
    
    // 添加新规则
    const newRule = {
        id: 1,
        priority: 1,
        action: {
            type: 'redirect',
            redirect: {
                regexSubstitution: `https://${targetDomain}/\\2`
            }
        },
        condition: {
            regexFilter: `^https?://(?:www\\.)?${sourceDomain}(/(.*))?$`,
            resourceTypes: ['main_frame']
        }
    };
    
    chrome.declarativeNetRequest.updateDynamicRules({
        addRules: [newRule]
    }).catch(error => {
        console.error('更新重定向规则失败:', error);
    });
}

// 当扩展安装时设置默认规则
chrome.runtime.onInstalled.addListener(function(details) {
    if (details.reason === 'install') {
        // 首次安装时设置默认值
        chrome.storage.local.set({
            sourceDomain: 'github.com',
            targetDomain: 'bgithub.xyz'
        }, function() {
            updateRedirectRules();
            console.log('默认设置已保存并应用');
        });
    }
});